﻿using System;
using System.Collections.Generic;
using System.IO;
using EasyLib.Configuration;

namespace EasyLib.Configuration
{
    /// <summary>
    /// class extends from AbstractConfig, which will load data from properties
    /// </summary>
    public class PropertiesConfig : FileConfig
    {
        internal protected PropertiesConfig(string configResource) : base(configResource) { }

        /// <summary>
        /// override method, read from properties file to retrieve config items and store in a collection
        /// </summary>
        public override void LoadData()
        {
            IDictionary<string, string> items = new Dictionary<string, string>();

            try
            {
                using (StreamReader sr = new StreamReader(ConfigFilePath))
                {
                    String line;

                    // Read and display lines from the file until the end of the file is reached.
                    while ((line = sr.ReadLine()) != null)
                    {
                        line = line.Trim();

                        if (line.StartsWith("#") || line.StartsWith(";"))
                        {
                        }

                        int ind = line.IndexOf('=');

                        if (ind < 0)
                        {
                            ind = line.IndexOf(':');
                        }
                        if (ind > 0)
                        {
                            string key = line.Substring(0, ind).Trim();
                            string value = line.Substring(ind + 1).Trim();

                            items[key] = value;
                        }
                    }
                    sr.Close();
                }
            }
            catch (Exception)
            {
                //TODO
            }

            if (items.Count != 0)
            {
                ConfigUtils.Cache[ConfigUtils.GetCategoryIfResxOrPropsFile(ConfigResource)] = items;
            }
        }
    }
}